<template>
  <div class="home-container">
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" />
      <div class="loading-text">加载中...</div>
    </div>
    
    <div v-else-if="error" class="error-container">
      <div class="error-icon">❌</div>
      <div class="error-text">{{ errorMessage }}</div>
      <van-button type="primary" class="retry-btn" @click="fetchData">重试</van-button>
    </div>
    
    <template v-else>
      <!-- 用户信息 -->
      <div class="user-info">
        <div class="username">{{ username }}</div>
        <div class="user-id">用户ID: {{ userId }}</div>
        <div class="read-only-badge">只读模式</div>
      </div>
      
      <!-- 总览模块 -->
      <div class="overview-card" @click="showIncomeExpenseDetail = true">
        <div class="overview-title">账户总览</div>
        <div class="overview-row">
          <div class="overview-item income">
            <span class="label">当前总额</span>
            <span class="amount">￥{{ formatNumber(overview.amount) }}</span>
          </div>
          <div class="overview-item income yesterday-item">
            <span class="label">昨日总额</span>
            <span class="amount">￥{{ formatNumber(overview.yesterdayAmount) }}</span>
          </div>
          <div class="overview-item" :class="growthAmount >= 0 ? 'income' : 'expense'">
            <span class="label">增长额</span>
            <span class="amount">￥{{ formatNumber(growthAmount) }}</span>
          </div>
        </div>
        <div class="overview-tip">点击查看明细</div>
      </div>
      
      <!-- 港币钱包模块 -->
      <div class="hkd-wallet-card">
        <div class="hkd-wallet-title">港币钱包</div>
        <div class="hkd-wallet-content">
          <div class="hkd-wallet-row">
            <span class="hkd-wallet-label">当前汇率</span>
            <div class="hkd-wallet-value">
              <span>{{ formatNumber(hkdWallet.rate, 3) }}</span>
            </div>
          </div>
          <div class="hkd-wallet-row">
            <span class="hkd-wallet-label">港币钱包</span>
            <div class="hkd-wallet-value">
              <span>HK$ {{ formatNumber(hkdWallet.amount) }}</span>
            </div>
          </div>
          <div class="hkd-wallet-row">
            <span class="hkd-wallet-label">折合人民币</span>
            <span class="hkd-wallet-value">￥{{ formatNumber(hkdWallet.cny) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 气泡明细 -->
      <van-popup v-model:show="showIncomeExpenseDetail" position="bottom" round :style="{ padding: '24px 0', borderRadius: '16px 16px 0 0' }">
        <div class="popup-detail">
          <div class="popup-title">总额明细</div>
          <div class="amount-overview">
            <div class="amount-overview-item">
              <div class="amount-label">当前总额</div>
              <div class="amount-value income">￥{{ formatNumber(overview.amount) }}</div>
            </div>
            <div class="amount-overview-item">
              <div class="amount-label">账户总额</div>
              <div class="amount-value income">￥{{ formatNumber(overview.accountAmount) }}</div>
            </div>
            <div class="amount-overview-item">
              <div class="amount-label">钱包总额</div>
              <div class="amount-value income">￥{{ formatNumber(overview.hkdCny) }}</div>
            </div>
          </div>
        </div>
      </van-popup>
      
      <!-- 账户列表 -->
      <div class="account-list-title">账户列表</div>
      <div class="account-list">
        <div
          class="account-card"
          v-for="account in accounts"
          :key="account.id"
          @click="goAccount(account.id)"
        >
          <div class="account-name">{{ account.name }}</div>
          <div class="account-amounts">
            <span class="total">总金额：<b>￥{{ account.total }}</b></span>
            <span class="ali">支付宝：￥{{ account.ali }}</span>
            <span class="wx">微信：￥{{ account.wx }}</span>
            <span class="bank">银行卡：￥{{ account.bank || 0 }}</span>
            <span class="credit-card">信用卡：￥{{ account.credit_card || 0 }}</span>
          </div>
        </div>
      </div>
      
      <div v-if="accounts.length === 0" class="empty-accounts">
        <div class="empty-icon">📭</div>
        <div class="empty-text">暂无账户数据</div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Loading, Button, Popup, showFailToast } from 'vant'
import { overviewApi, accountApi, getUserInfo } from '@/api'
import dateUtils from '@/utils/date'
import numberUtils from '@/utils/number'
import moneyUtils from '@/utils/money'

const route = useRoute()
const router = useRouter()
const userId = ref(atob(route.params.userId))
const username = ref('')
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const showIncomeExpenseDetail = ref(false)

const overview = ref({
  income: 0,
  expense: 0,
  wxIncome: 0,
  aliIncome: 0,
  bankIncome: 0,
  wxExpense: 0,
  aliExpense: 0,
  bankExpense: 0,
  amount: 0,
  accountAmount: 0,
  hkdCny: 0,
  yesterdayAmount: 0
})

const hkdWallet = ref({
  amount: 0,
  rate: 0.935,
  cny: 0
})

const accounts = ref([])

// 计算增长金额（账户总额 - 昨日总额）
const growthAmount = computed(() => {
  const currentAmount = overview.value.amount || 0;
  const yesterdayAmount = overview.value.yesterdayAmount || 0;
  return moneyUtils.subtract(currentAmount, yesterdayAmount);
})

function formatNumber(value, decimals) {
  return moneyUtils.formatMoney(value, decimals);
}

async function fetchData() {
  if (!userId.value) {
    error.value = true
    errorMessage.value = '缺少用户ID参数'
    loading.value = false
    return
  }
  
  loading.value = true
  error.value = false
  
  try {
    // 并行请求数据，移除对getUserInfo的调用
    const [overviewRes, accountsRes] = await Promise.all([
      overviewApi.getOverview(userId.value),
      accountApi.getAccounts(userId.value)
    ]);
    
    // 从overview中获取用户名
    if (overviewRes && overviewRes.user) {
      username.value = overviewRes.user.username;
    }
    
    // 设置港币钱包信息
    if (overviewRes && overviewRes.hkdWallet) {
      hkdWallet.value = overviewRes.hkdWallet;
    }
    
    // 设置总览数据
    overview.value = overviewRes;
    
    // 设置账户列表
    accounts.value = accountsRes;
    
    loading.value = false;
  } catch (err) {
    console.error('获取数据失败:', err);
    error.value = true;
    errorMessage.value = err.response?.data?.error || '获取数据失败';
    loading.value = false;
    showFailToast(errorMessage.value);
  }
}

function goAccount(accountId) {
  router.push(`/user/${btoa(userId.value)}/account/${accountId}`);
}

onMounted(() => {
  fetchData();
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: #f6f7fb;
  padding: 16px 16px 80px 16px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
}

.loading-text {
  margin-top: 16px;
  color: #666;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-text {
  color: #ff4d4f;
  margin-bottom: 16px;
  text-align: center;
}

.retry-btn {
  margin-top: 16px;
}

.user-info {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  padding: 16px;
  margin-bottom: 16px;
  position: relative;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.user-id {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.read-only-badge {
  position: absolute;
  top: 16px;
  right: 16px;
  background: #ff9800;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.overview-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  padding: 16px;
  margin-bottom: 16px;
}

.overview-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.overview-row {
  display: flex;
  justify-content: space-between;
}

.overview-item {
  flex: 1;
  text-align: center;
}

.label {
  font-size: 14px;
  color: #666;
}

.amount {
  display: block;
  font-size: 16px;
  font-weight: 500;
  margin-top: 4px;
}

.income .amount {
  color: #27c19e;
}

.expense .amount {
  color: #ff4d4f;
}

.overview-tip {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 12px;
}

.hkd-wallet-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  padding: 16px;
  margin-bottom: 16px;
}

.hkd-wallet-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.hkd-wallet-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.hkd-wallet-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hkd-wallet-label {
  font-size: 14px;
  color: #666;
}

.hkd-wallet-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.popup-detail {
  padding: 0 16px;
}

.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  text-align: center;
}

.amount-overview {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.amount-overview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-label {
  font-size: 14px;
  color: #666;
}

.amount-value {
  font-size: 16px;
  font-weight: 500;
}

.amount-value.income {
  color: #27c19e;
}

.account-list-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 16px 0 12px 0;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.account-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  padding: 16px;
}

.account-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.account-amounts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.account-amounts span {
  font-size: 13px;
  color: #666;
  margin-right: 8px;
}

.account-amounts .total b {
  color: #27c19e;
}

.empty-accounts {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  color: #999;
}
</style> 